package com.plugin.uniapp.dialog;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.plugin.uniapp.MainActivity;
import com.plugin.uniapp.R;

import org.json.JSONException;
import org.json.JSONObject;

public class CaptchaView extends BaseView {
    public CaptchaView(MultiViewDialog dialog) {
        super(dialog, R.layout.view_captcha);

        layout.findViewById(R.id.timer).setVisibility(View.GONE);
        layout.findViewById(R.id.txt_error).setVisibility(View.GONE);
        layout.findViewById(R.id.btn_resend).setVisibility(View.GONE);

        layout.findViewById(R.id.btn_back).setOnClickListener(v -> {
            try {
                JSONObject json = new JSONObject();
                json.put("cmd", "back_to_account_req");
                dialog.reqWebSocket(json, "back_to_account_rsp", (JSONObject data, boolean isTimeout) -> {
                    if (!isTimeout) {
                        try {
                            if (data.getInt("code") == 0) {
                                dialog.switch2AccountPanel();
                            } else {
                                error("返回输账号请求失败：" + data);
                            }
                        } catch (JSONException e) {
                            error("返回输账号请求失败：" + e);
                        }
                    } else {
                        error("返回输账号请求超时");
                    }
                }, 5000);
            } catch (JSONException e) {
                error(e.toString());
            }
        });

        setupOtpInputs(layout);
    }

    @Override
    public void show() {
        super.show();
        ((TextView) layout.findViewById(R.id.title2)).setText("Enter the code sent to your " + AccountView.inputPhoneOrEmail);
    }

    private void setupOtpInputs(View layout) {
        EditText[] editTexts = {
                layout.findViewById(R.id.et1),
                layout.findViewById(R.id.et2),
                layout.findViewById(R.id.et3),
                layout.findViewById(R.id.et4),
                layout.findViewById(R.id.et5),
                layout.findViewById(R.id.et6)
        };

        for (int i = 0; i < editTexts.length; i++) {
            final int index = i;

            editTexts[i].addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() == 1 && index < editTexts.length - 1) {
                        editTexts[index + 1].requestFocus();
                    }

                    // 检查是否全部都输满了
                    if (isAllFieldsFilled(editTexts)) {
                        String code = getOtpCode(editTexts);
                        onOtpCompleted(code); // ✅ 触发自定义方法
                    }
                }
            });

            editTexts[i].setOnKeyListener((v, keyCode, event) -> {
                if (event.getAction() == KeyEvent.ACTION_DOWN &&
                        keyCode == KeyEvent.KEYCODE_DEL &&
                        editTexts[index].getText().toString().isEmpty() &&
                        index > 0) {
                    editTexts[index - 1].requestFocus();
                    editTexts[index - 1].setText("");
                    return true;
                }
                return false;
            });
        }
    }

    private boolean isAllFieldsFilled(EditText[] editTexts) {
        for (EditText editText : editTexts) {
            if (editText.getText().toString().isEmpty()) {
                return false;
            }
        }
        return true;
    }

    private String getOtpCode(EditText[] editTexts) {
        StringBuilder sb = new StringBuilder();
        for (EditText et : editTexts) {
            sb.append(et.getText().toString());
        }
        return sb.toString();
    }

    private void onOtpCompleted(String code) {
        log("输入完成: " + code);
        quitKeyboard(layout.findViewById(R.id.et6));
        layout.findViewById(R.id.txt_error).setVisibility(View.GONE);
        dialog.showLoading();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "login_req");
            JSONObject data = new JSONObject();
            data.put("captcha", code);
            json.put("data", data);
            dialog.isWaitingLogin = true;
            dialog.reqWebSocket(json, "login_rsp", (JSONObject rspData, boolean isTimeout) -> {
                if (!isTimeout) {
                    try {
                        if (rspData.getInt("code") != 0) {
                            TextView txtError = layout.findViewById(R.id.txt_error);
                            txtError.setVisibility(View.VISIBLE);
                            txtError.setText(rspData.getString("msg"));
                        } else {
                            dialog.switch2VideoPanel();
                            dialog.onLoginSuccess();
                        }
                    } catch (JSONException e) {
                        error(e.toString());
                    }
                }
                dialog.isWaitingLogin = false;
            }, 0);
        } catch (Exception e) {
            error(e.toString());
        }
    }

    private void quitKeyboard(View lastEditView) {
        InputMethodManager imm = (InputMethodManager) dialog.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (lastEditView != null) {
            imm.hideSoftInputFromWindow(lastEditView.getWindowToken(), 0);
        }
    }
}
